import { Component, OnInit } from '@angular/core';
import { Hero } from '../heroes/class/hero'
import { HeroService } from '../hero.service'
import { Observable, Subject } from 'rxjs'
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'
@Component({
  selector: 'app-hero-search',
  templateUrl: './hero-search.component.html',
  styleUrls: ['./hero-search.component.scss']
})
export class HeroSearchComponent implements OnInit {
  heroes$: Observable<Hero[]>;
  private searchTerms = new Subject<string>();
  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.heroes$ = this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) =>{ console.log(term);return this.heroService.searchHero(term)})
    );
  }
  // Push a search term into the observable stream.
  searchHero(term: string): void {
    this.searchTerms.next(term);
  }
}
